<template>
  <div class="address-edit">
    <van-nav-bar :title="index >= 0 ? '编辑收货地址' : '新增收货地址'" left-arrow @click-left="$router.go(-1)" />
    <van-address-edit
      :addressInfo="addressInfo"
      :area-list="areaList"
      show-postal
      show-delete
      show-set-default
      show-search-result
      :area-columns-placeholder="['请选择', '请选择', '请选择']"
      @save="onSave"
      @delete="onDelete"
    >
    </van-address-edit>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { areaList } from '@vant/area-data'
import { addAddress, delAddress } from '@/api/address'
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'AddressEdit',
  computed: {
    ...mapState('address', ['addressList'])
  },
  data () {
    return {
      index: null,
      id: null,
      areaList,
      searchResult: [],
      addressInfo: {}
    }
  },
  created () {
    this.index = this.$route.params.index
    if (this.index !== undefined && this.index < this.addressList.length) {
      this.id = this.addressList[this.index].id
      this.addressInfo = this.addressList[this.index]
    } else {
      // 新增地址
      this.addressInfo = {}
    }
  },
  // 可以添加其他方法和钩子
  methods: {
    ...mapMutations('address', ['delAddressById']),
    async onSave (content) {
      await this.addUserAddress(content)
    },
    async onDelete (res) {
      await this.delUserAddress(res)
    },
    // 保存用户地址
    async addUserAddress (content) {
      // 无id为保存
      if (typeof this.index !== 'undefined') {
        // 有id为编辑
        content.id = this.id
      }
      const { msg } = await addAddress(content)
      // 提示成功
      Toast(msg)
      // 清空表单
      this.addressInfo = {}
      // 返回地址列表页
      this.$router.push('/address')
    },
    // 删除用户地址
    async delUserAddress (res) {
      // 删除本地
      this.delAddressById(this.index)
      // 删除服务器端
      const { msg } = await delAddress(this.id)
      // 提示成功
      Toast(msg)
      // 返回地址列表页
      this.$router.push('/address')
    }
  }
}
</script>

<style lang="less" scoped></style>
